package com.ethank.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ethank.common.core.text.Convert;
import com.ethank.common.exception.ServiceException;
import com.ethank.common.utils.StringUtils;
import com.ethank.common.utils.uuid.IdUtils;
import com.ethank.entity.oaBill.*;
import com.ethank.mapper.FnaInvoiceLedgerMapper;
import com.microsoft.sqlserver.jdbc.SQLServerException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @author Administrator
 * 混贴发票数据处理
 */
@Component
public class BillDataUtil {


    public static BillDataUtil billDataUtil;
    @Resource
    FnaInvoiceLedgerMapper fnaInvoiceLedgerMapper;

    @PostConstruct
    public void init() {
        billDataUtil = this;
        billDataUtil.fnaInvoiceLedgerMapper = this.fnaInvoiceLedgerMapper;
    }

    /**
     * 增值税1
     *
     * @param dataInfo 数据
     * @param ftype    原件/复印件
     * @param typeInt  票据类型
     * @desc 增值税发票数据处理
     * @auther Administrator
     */
    public void recognizeInvoiceData(JSONObject dataInfo, String ftype, Integer typeInt) {
        // 公共属性，每个方法首先进行公共属性的装载
        commonInvoiceInsert(dataInfo, typeInt);

    }

    /**
     * 定额发票5
     */
    public void quotaInvoice(JSONObject dataInfo, String ftype, Integer typeInt) {
        // 公共属性，每个方法首先进行公共属性的装载
        commonInvoiceInsert(dataInfo, typeInt);

    }


    /**
     * 航空行程单14
     */
    public void airItinerary(JSONObject dataInfo, String ftype, Integer typeInt) {
        // 公共属性，每个方法首先进行公共属性的装载
        Fnainvoiceledger fnainvoiceledger = commonInvoiceInsert(dataInfo, typeInt);
        if (dataInfo.containsKey("id") && null != dataInfo.getInteger("id")) {
            // 删除原数据
            BillDataUtil.billDataUtil.fnaInvoiceLedgerMapper.deleteairInvoice(dataInfo.getInteger("id"));
        }
        // 航空行程单主表内容赋值
        AirInvoice airInvoice = new AirInvoice();
        airInvoice.setId(IdUtils.simpleUUID());
        airInvoice.setMainid(fnainvoiceledger.getId());
        // 乘机人姓名
        airInvoice.setUser_name(dataInfo.getString("passengerName") == null ? "" : dataInfo.getString("passengerName"));
        // 身份证号
        airInvoice.setUser_id(dataInfo.getString("idCardNumber") == null ? "" : dataInfo.getString("idCardNumber"));
        // 销售单位代号
        airInvoice.setAgentcode(dataInfo.getString("agentCode") == null ? "" : dataInfo.getString("agentCode"));
        // 填开单位
        airInvoice.setIssue_by(dataInfo.getString("issueCompany") == null ? "" : dataInfo.getString("issueCompany"));
        // 票价
        airInvoice.setFare(dataInfo.getString("fare") == null ? "" : dataInfo.getString("fare"));
        // 燃油附加费
        airInvoice.setFuel_surcharge(dataInfo.getString("fuelSurcharge") == null ? "" : dataInfo.getString(
                "fuelSurcharge"));
        // 民航发展基金
        airInvoice.setCaac_development_fund(dataInfo.getString("caacDevelopmentFund") == null ? "" :
                dataInfo.getString("caacDevelopmentFund"));
        // 保险费
        airInvoice.setInsurance(dataInfo.getString("insurance") == null ? "" : dataInfo.getString("insurance"));
        billDataUtil.fnaInvoiceLedgerMapper.addAirPlane(airInvoice);


        // 航空行程单详细信息组合
        ArrayList<AirInvoiceDetail> airInvoiceDetails = new ArrayList<>();
        try {
            if (StringUtils.isNotBlank(dataInfo.getString("flights")) && dataInfo.getJSONArray("flights").size() > 0) {

                dataInfo.getJSONArray("flights").forEach(e -> {
                    System.out.println("e=>" + e.toString());
                    JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(e));
                    // 航空行程单详情表内容赋值
                    AirInvoiceDetail airInvoiceDetail = new AirInvoiceDetail();
                    airInvoiceDetail.setId(IdUtils.simpleUUID());
                    airInvoiceDetail.setMainid(fnainvoiceledger.getId());
                    // 出发站
                    airInvoiceDetail.setFrom_city(jsonObject.getString("departureStation") == null ? "" :
                            jsonObject.getString("departureStation"));
                    // 到达站
                    airInvoiceDetail.setTo_city(jsonObject.getString("arrivalStation") == null ? "" :
                            jsonObject.getString("arrivalStation"));
                    // 航班号
                    airInvoiceDetail.setFlight_number(jsonObject.getString("flightNumber") == null ? "" :
                            jsonObject.getString("flightNumber"));
                    // 乘机日期
                    airInvoiceDetail.setAirdate(jsonObject.getString("flightDate") == null ? "" :
                            jsonObject.getString("flightDate"));
                    // 乘机时间
                    airInvoiceDetail.setAirtime(jsonObject.getString("flightTime") == null ? "" :
                            jsonObject.getString("flightTime"));
                    // 座位等级
                    airInvoiceDetail.setSeat(jsonObject.getString("seatClass") == null ? "" : jsonObject.getString(
                            "seatClass"));
                    // 承运人
                    airInvoiceDetail.setCarrier(jsonObject.getString("carrier") == null ? "" : jsonObject.getString(
                            "carrier"));
                    airInvoiceDetails.add(airInvoiceDetail);
                });
                billDataUtil.fnaInvoiceLedgerMapper.addAirPlaneDetail(airInvoiceDetails);
            }
        } catch (Exception e) {
            e.getMessage();
            System.out.println(" 机票行程单详情添加失败");
        }
    }

    /**
     * 火车票8
     */
    public void trainInvoice(JSONObject dataInfo, String ftype, Integer typeInt) {
        // 公共属性，每个方法首先进行公共属性的装载
        Fnainvoiceledger fnainvoiceledger = commonInvoiceInsert(dataInfo, typeInt);
        if (dataInfo.containsKey("id") && null != dataInfo.getInteger("id")) {
            // 删除原数据
            BillDataUtil.billDataUtil.fnaInvoiceLedgerMapper.deletetrainInvoice(dataInfo.getInteger("id"));
        }

        // 装载数据
        TrainInvoice trainInvoice = new TrainInvoice();
        trainInvoice.setId(IdUtils.simpleUUID());
        trainInvoice.setMainid(fnainvoiceledger.getId());
        trainInvoice.setStation_getoff(dataInfo.getString("arrivalStation") == null ? "" : dataInfo.getString(
                "arrivalStation"));
        trainInvoice.setTrain_number(dataInfo.getString("trainNumber") == null ? "" : dataInfo.getString("trainNumber"
        ));
        trainInvoice.setSeat(dataInfo.getString("seatType") == null ? "" : dataInfo.getString("seatType"));
        trainInvoice.setTime(dataInfo.getString("departureTime") == null ? "" : dataInfo.getString("departureTime"));
        trainInvoice.setName(dataInfo.getString("passengerName") == null ? "" : dataInfo.getString("passengerName"));
        trainInvoice.setStation_geton(dataInfo.getString("departureStation") == null ? "" : dataInfo.getString(
                "departureStation"));
        billDataUtil.fnaInvoiceLedgerMapper.addTrainTicket(trainInvoice);
    }

    /**
     * 出租车7
     */
    public void taxiInvoice(JSONObject dataInfo, String ftype, Integer typeInt) {
        // 公共属性，每个方法首先进行公共属性的装载

        Fnainvoiceledger fnainvoiceledger = commonInvoiceInsert(dataInfo, typeInt);

        if (dataInfo.containsKey("id") && null != dataInfo.getInteger("id")) {
            // 删除原数据
            BillDataUtil.billDataUtil.fnaInvoiceLedgerMapper.deletetaxiInvoice(dataInfo.getInteger("id"));
        }

        // 装载数据
        TaxiInvoice taxiInvoice = new TaxiInvoice();
        taxiInvoice.setId(IdUtils.simpleUUID());
        taxiInvoice.setMainid(fnainvoiceledger.getId());
        taxiInvoice.setTime_geton(dataInfo.getString("pickUpTime") == null ? "" : dataInfo.getString("pickUpTime"));
        taxiInvoice.setTime_getoff(dataInfo.getString("dropOffTime") == null ? "" : dataInfo.getString("dropOffTime"));
        taxiInvoice.setMileage(dataInfo.getString("mileage") == null ? "" : dataInfo.getString("mileage"));
        taxiInvoice.setFare(dataInfo.getString("fare") == null ? "" : dataInfo.getString("fare"));
        taxiInvoice.setLicense_plate(dataInfo.getString("licensePlateNumber") == null ? "" : dataInfo.getString(
                "licensePlateNumber"));
        // 发票所在地
        taxiInvoice.setPlace("");
        billDataUtil.fnaInvoiceLedgerMapper.addTaxiData(taxiInvoice);
    }


    /**
     * 增值税发票卷票16
     */
    public void rollTicket(JSONObject dataInfo, String ftype, Integer typeInt) {
        // 公共属性，每个方法首先进行公共属性的装载
        commonInvoiceInsert(dataInfo, typeInt);

    }

    /**
     * 客运车船票10
     */
    public void busShipTicket(JSONObject dataInfo, String ftype, Integer typeInt) {
        // 公共属性，每个方法首先进行公共属性的装载
        Fnainvoiceledger fnainvoiceledger = commonInvoiceInsert(dataInfo, typeInt);
        if (dataInfo.containsKey("id") && null != dataInfo.getInteger("id")) {
            // 删除原数据
            BillDataUtil.billDataUtil.fnaInvoiceLedgerMapper.deletecarInvoice(dataInfo.getInteger("id"));
        }
        CarInvoice carInvoice = new CarInvoice();
        String dateStr = dataInfo.getString("date") == null ? "" : dataInfo.getString("date");
        String timeStr = dataInfo.getString("time") == null ? "" : dataInfo.getString("time");
        carInvoice.setId(IdUtils.simpleUUID());
        carInvoice.setMainid(fnainvoiceledger.getId());
        carInvoice.setTime(dateStr + " " + timeStr);
        carInvoice.setStation_geton(dataInfo.getString("departureStation") == null ? "" : dataInfo.getString(
                "departureStation"));
        carInvoice.setStation_getoff(dataInfo.getString("arrivalStation") == null ? "" : dataInfo.getString(
                "arrivalStation"));
        carInvoice.setName(dataInfo.getString("passengerName") == null ? "" : dataInfo.getString("passengerName"));
        billDataUtil.fnaInvoiceLedgerMapper.addCarShipTicket(carInvoice);
    }


    /**
     * 通用机打发票3
     */
    public void commonPrintedInvoice(JSONObject dataInfo, String ftype, Integer typeInt) {
        if (dataInfo.containsKey("id") && null != dataInfo.getInteger("id")) {
            // 删除原数据
            BillDataUtil.billDataUtil.fnaInvoiceLedgerMapper.deletemachineInvoice(dataInfo.getInteger("id"));
        }
        Fnainvoiceledger fnainvoiceledger = commonInvoiceInsert(dataInfo, typeInt);
        // 装载数据
        MachineInvoice machineInvoice = new MachineInvoice();
        machineInvoice.setId(IdUtils.simpleUUID());
        machineInvoice.setMainid(fnainvoiceledger.getId());
        machineInvoice.setTime(dataInfo.getString("invoiceDate") == null ? "" : dataInfo.getString("invoiceDate"));
        machineInvoice.setCategory(dataInfo.getString("formType") == null ? "" : dataInfo.getString("formType"));
        machineInvoice.setSeller_tax_id(dataInfo.getString("sellerTaxNumber") == null ? "" : dataInfo.getString(
                "sellerTaxNumber"));
        machineInvoice.setBuyer_tax_id(dataInfo.getString("purchaserTaxNumber") == null ? "" : dataInfo.getString(
                "purchaserTaxNumber"));
        billDataUtil.fnaInvoiceLedgerMapper.addCommonInvoice(machineInvoice);

    }

    /**
     * 网约车行程单21
     */
    public void rideHailingItinerary(JSONObject dataInfo, String ftype, Integer typeInt) {
        // 公共属性，每个方法首先进行公共属性的装载
        Fnainvoiceledger fnainvoiceledger = commonInvoiceInsert(dataInfo, typeInt);
        if (dataInfo.containsKey("id")) {
            // 删除原数据
            BillDataUtil.billDataUtil.fnaInvoiceLedgerMapper.deletetaxiInvoice(dataInfo.getInteger("id"));
        }
        // 装载数据
        TaxiInvoice taxiInvoice = new TaxiInvoice();
        taxiInvoice.setId(IdUtils.simpleUUID());
        taxiInvoice.setMainid(fnainvoiceledger.getId());
        taxiInvoice.setTime_geton(dataInfo.getString("pickUpTime") == null ? "" : dataInfo.getString("pickUpTime"));
        taxiInvoice.setTime_getoff(dataInfo.getString("dropOffTime") == null ? "" : dataInfo.getString("dropOffTime"));
        taxiInvoice.setMileage(dataInfo.getString("mileage") == null ? "" : dataInfo.getString("mileage"));
        // 发票所在地
        taxiInvoice.setPlace(dataInfo.getString("city") == null ? "" : dataInfo.getString("city"));
        billDataUtil.fnaInvoiceLedgerMapper.addTaxiData(taxiInvoice);
    }

    /**
     * 过路过桥费发票9 √
     */
    public void tollInvoice(JSONObject dataInfo, String ftype, Integer typeInt) {
        // 公共属性，每个方法首先进行公共属性的装载

        Fnainvoiceledger fnainvoiceledger = commonInvoiceInsert(dataInfo, typeInt);
        if (dataInfo.containsKey("id") && null != dataInfo.getInteger("id")) {
            // 删除原数据
            BillDataUtil.billDataUtil.fnaInvoiceLedgerMapper.deletetollInvoice(dataInfo.getInteger("id"));
        }

        ArrayList<FnainvoiceledgerDetail> fnainvoiceledgerDetails = new ArrayList<>();
        // 台账明细表内容赋值

        FnainvoiceledgerDetail fnainvoiceledgerDetail = fnainvoiceledgerDetailData(dataInfo, fnainvoiceledger.getId());
        // 金额
        fnainvoiceledgerDetail.setPricewithouttax(dataInfo.getString("totalAmount") == null ? new BigDecimal("0") :
                new BigDecimal(dataInfo.getString("totalAmount")));
        // 原始单价
        fnainvoiceledgerDetail.setOriginalUnitPrice(dataInfo.getString("totalAmount") == null ? "" :
                dataInfo.getString("totalAmount"));
        fnainvoiceledgerDetails.add(fnainvoiceledgerDetail);
        billDataUtil.fnaInvoiceLedgerMapper.addDataDetail(fnainvoiceledgerDetails);


        // 装载数据
        TollInvoice tollInvoice = new TollInvoice();
        tollInvoice.setId(IdUtils.simpleUUID());
        tollInvoice.setMainid(fnainvoiceledger.getId());
        tollInvoice.setTime(dataInfo.getString("time") == null ? "" : dataInfo.getString("time"));
        tollInvoice.setEntrance(dataInfo.getString("entranceName") == null ? "" : dataInfo.getString("entranceName"));
        tollInvoice.setExport(dataInfo.getString("exitName") == null ? "" : dataInfo.getString("exitName"));
        billDataUtil.fnaInvoiceLedgerMapper.addTollBridge(tollInvoice);
    }


    /**
     * 主表 发票台账表 数据
     */
    public Fnainvoiceledger fnainvoiceledgerData(JSONObject jsonObject, Integer typeInt) {
        // 主表 台账表 ID
        // String id = IdUtils.simpleUUID();
        // 发票台账表
        // Fnainvoiceledger fnainvoiceledger = new Fnainvoiceledger();
        Fnainvoiceledger fnainvoiceledger = fnainvoiceledgerImportData(typeInt, null);
//        String id = IdUtils.simpleUUID();
//        // OCR图片id
        fnainvoiceledger.setImageDocId(jsonObject.getInteger("ocrDocId"));
        // 买方税号
        fnainvoiceledger.setPurchasertaxno(jsonObject.getString("purchaserTaxNumber") == null ? "" :
                jsonObject.getString("purchaserTaxNumber"));
        // 卖方税号
        fnainvoiceledger.setSalestaxno(jsonObject.getString("sellerTaxNumber") == null ? "" : jsonObject.getString(
                "sellerTaxNumber"));
        // 发票归属人
        fnainvoiceledger.setUserid_new(jsonObject.getInteger("userId"));
        // 发票来源
        fnainvoiceledger.setInvoicesource_new("4");
        // 发票校验码
        fnainvoiceledger.setCheckcode(jsonObject.getString("checkCode") == null ? "" : jsonObject.getString(
                "checkCode"));
        // 发票状态
        fnainvoiceledger.setStatus("0");
        // 微信电子发票card_id
        fnainvoiceledger.setCard_id_new("");
        fnainvoiceledger.setEncrypt_code_new("");
        fnainvoiceledger.setOpenid_new("");
        fnainvoiceledger.setWechatstatus("");
        // 开票日期 转换成时间戳秒
        if (StringUtils.isNotBlank(jsonObject.getString("invoiceDate"))) {
            Long invoiceDate = DateCovertUtil.getTimeStamp(jsonObject.getString("invoiceDate"));
            fnainvoiceledger.setBillingdate(invoiceDate > 0 ? DateCovertUtil.secondsToFormat(invoiceDate, "yyyy-MM-dd"
            ) : "");

        }
        // 发票代码
        fnainvoiceledger.setInvoicecode(jsonObject.getString("invoiceCode") == null ? "" : jsonObject.getString(
                "invoiceCode"));
        if ((jsonObject.getString("invoiceCode") == null || "".equals(jsonObject.getString("invoiceCode"))) && jsonObject.getString("ticketCode") != null && !"".equals(jsonObject.getString("ticketCode"))) {
            // 发票号码
            fnainvoiceledger.setInvoicecode(jsonObject.getString("ticketCode"));
        }
        // 发票号码
        fnainvoiceledger.setInvoicenumber(jsonObject.getString("invoiceNumber") == null ? "" : jsonObject.getString(
                "invoiceNumber"));
        if ((jsonObject.getString("invoiceNumber") == null || "".equals(jsonObject.getString("invoiceNumber"))) && jsonObject.getString("ticketNumber") != null && !"".equals(jsonObject.getString("ticketNumber"))) {
            // 发票号码
            fnainvoiceledger.setInvoicenumber(jsonObject.getString("ticketNumber"));
        }
//        // 发票类型
//        fnainvoiceledger.setInvoicetype(typeInt);
        // 销售方名称
        fnainvoiceledger.setSeller(jsonObject.getString("sellerName") == null ? "" : jsonObject.getString("sellerName"
        ));
        // 购买方名称
        fnainvoiceledger.setPurchaser(jsonObject.getString("purchaserName") == null ? "" : jsonObject.getString(
                "purchaserName"));
        // 货物或应税服务类型
        fnainvoiceledger.setInvoiceserviceyype(jsonObject.getString("invoiceType") == null ? "" :
                jsonObject.getString("invoiceType"));

        // 金额（不含税价）
        fnainvoiceledger.setPricewithouttax(jsonObject.getString("invoiceAmountPreTax") == null ? "0" :
                jsonObject.getString("invoiceAmountPreTax"));
        // 税率
        if (jsonObject.containsKey("invoiceDetails") && StringUtils.isNotBlank(jsonObject.getString("invoiceDetails"))) {
            JSONArray invoiceDetails = new JSONArray();
            try {
                invoiceDetails = jsonObject.getJSONArray("invoiceDetails");
            } catch (Exception e) {
                System.out.println("发票详情解析失败");
                e.getMessage();
            }

            if (null != invoiceDetails && invoiceDetails.size() > 0) {
                JSONObject invoiceJson = JSON.parseObject(JSON.toJSONString(invoiceDetails.get(0)));
                if (invoiceJson.getString("taxRate") != null) {
                    String taxrate = invoiceJson.getString("taxRate").replace("%", "");
                    // fnainvoiceledger.setTaxrate(taxrate);
                    fnainvoiceledger.setTaxrate(Convert.toBigDecimal(taxrate,new BigDecimal("0")).toString());
                } else {
                    fnainvoiceledger.setTaxrate("0");
                }
            }else{
                fnainvoiceledger.setTaxrate("0");
            }

        }else{
            fnainvoiceledger.setTaxrate("0");
        }
        // 税额（税价）
        fnainvoiceledger.setTax(jsonObject.getString("invoiceTax") == null ? "0" : jsonObject.getString("invoiceTax"));
        // 价税合计（含税价）
        if (jsonObject.containsKey("taxincludedprice") && StringUtils.isNotBlank(jsonObject.getString(
                "taxincludedprice"))) {
            fnainvoiceledger.setTaxincludedprice(jsonObject.getString("taxincludedprice"));
        }
        if (StringUtils.isBlank(fnainvoiceledger.getTaxincludedprice())) {
            fnainvoiceledger.setTaxincludedprice(jsonObject.getString("totalAmount"));
        }
        if (StringUtils.isBlank(fnainvoiceledger.getTaxincludedprice())) {
            fnainvoiceledger.setTaxincludedprice(jsonObject.getString("fare"));
        }
        if (StringUtils.isBlank(fnainvoiceledger.getTaxincludedprice())) {
            fnainvoiceledger.setTaxincludedprice(jsonObject.getString("Amount"));
        }
        if(StringUtils.isBlank(fnainvoiceledger.getTaxincludedprice())){
            fnainvoiceledger.setTaxincludedprice("0");
        }
        // 发票类型 增值税类型 是专用票  invoiceType则需要修改 2
        if(fnainvoiceledger.getInvoicetype().equals(1) &&  fnainvoiceledger.getInvoiceserviceyype().contains("专用")){
            fnainvoiceledger.setInvoicetype(2);
        }else if(fnainvoiceledger.getInvoicetype().equals(1) &&  fnainvoiceledger.getInvoiceserviceyype().equals("普通发票")){
            //增值税发票 不带专用 税率、税额设为0
            fnainvoiceledger.setTaxrate("0");

        }
        //飞机票、火车票税率 9%
        if(fnainvoiceledger.getInvoicetype().equals(8) || fnainvoiceledger.getInvoicetype().equals(14)){
            fnainvoiceledger.setTaxrate("9");
        }
        //客运车船票实名 税率 3%
        if(fnainvoiceledger.getInvoicetype().equals(10) && StringUtils.isNotBlank(jsonObject.getString("passengerName"))){
            fnainvoiceledger.setTaxrate("3");
        }
        //税率 取绝对值防止税率为负数
        BigDecimal taxRate = Convert.toBigDecimal(Math.abs(Convert.toInt(fnainvoiceledger.getTaxrate(),0)),BigDecimal.ZERO);
        //税率是0 则税额为0 含税价和非税价相等
        if(taxRate.compareTo(BigDecimal.ZERO) == 0){
            fnainvoiceledger.setPricewithouttax(fnainvoiceledger.getTaxincludedprice());
            fnainvoiceledger.setTax(BigDecimal.ZERO.toString());
        }else{

            // 重新计算含税价和非含税价
            BigDecimal divisor = taxRate.divide(new BigDecimal(100)).add(new BigDecimal(1));
            BigDecimal newTax = Convert.toBigDecimal(fnainvoiceledger.getTaxincludedprice(), BigDecimal.ZERO).divide(divisor, 2, RoundingMode.HALF_EVEN).multiply(taxRate.divide(new BigDecimal(100),2, RoundingMode.HALF_EVEN));
            fnainvoiceledger.setTax(newTax.toString());
            BigDecimal priceWithoutTax = Convert.toBigDecimal(fnainvoiceledger.getTaxincludedprice(), BigDecimal.ZERO).subtract(newTax);
            fnainvoiceledger.setPricewithouttax(priceWithoutTax.toString());
        }

        // 发票真伪
        fnainvoiceledger.setAuthenticity(0);
        // 报销日期
        fnainvoiceledger.setReimbursementdate("");
        // 报销人
        fnainvoiceledger.setReimburseperson(jsonObject.getString("userId"));
//        // 流程requestId
//        fnainvoiceledger.setRequestid(IdUtils.simpleUUID());
        // 录入时间
        // fnainvoiceledger.setEntryTime();
        // 是否有公司印章
        fnainvoiceledger.setCompany_seal("");
        // 发票是第几联
        fnainvoiceledger.setForm_type("");
        // 发票联次
        fnainvoiceledger.setForm_name(jsonObject.getString("formType") == null ? "" : jsonObject.getString("formType"));
        // 发票消费类型
        fnainvoiceledger.setKind(jsonObject.getString("invoiceType") == null ? "" : jsonObject.getString("invoiceType"
        ));
        // 密码区
        fnainvoiceledger.setCiphertext(jsonObject.getString("passwordArea") == null ? "" : jsonObject.getString(
                "passwordArea"));
        // 种类
        fnainvoiceledger.setCategory(jsonObject.getString("type") == null ? "" : jsonObject.getString("type"));
        // 发票查验状态
        fnainvoiceledger.setCheckStatus(jsonObject.getOrDefault("checkStatus", "0").toString());
        // 扩展表字段 -------------------
//        // 主键
        if (jsonObject.containsKey("id") && StringUtils.isNotBlank(jsonObject.getString("id"))) {
            fnainvoiceledger.setIdVo(jsonObject.getString("id"));

        }
        // 表FnaInvoiceLedger主键
        fnainvoiceledger.setMainId(fnainvoiceledger.getId());
        // 备注
        fnainvoiceledger.setRemark(jsonObject.getString("remarks") == null ? "" : jsonObject.getString("remarks"));
        // 校验码后六位
        fnainvoiceledger.setCheckCodeSix("");
        // 销售方地址、电话
        fnainvoiceledger.setSellerAddress(jsonObject.getString("sellerContactInfo") == null ? "" :
                jsonObject.getString("sellerContactInfo"));
        // 定额发票、过路过桥、客运车船费
        if (Arrays.asList(5, 9, 10).contains(typeInt)) {
            fnainvoiceledger.setSeller(String.valueOf(jsonObject.getOrDefault("title", "")));
        }
        // 机票
        if (Integer.valueOf(14).equals(typeInt)) {
            fnainvoiceledger.setSeller(String.valueOf(jsonObject.getOrDefault("issueCompany", "")));
        }
        // 购买方地址、电话
        fnainvoiceledger.setPurchaserAddress(jsonObject.getString("purchaserContactInfo") == null ? "" :
                jsonObject.getString("purchaserContactInfo"));
        // 销售方开户行及账号
        fnainvoiceledger.setSalesBank(jsonObject.getString("sellerBankAccountInfo") == null ? "" :
                jsonObject.getString("sellerBankAccountInfo"));
        // 购买方开户行及账号
        fnainvoiceledger.setPurchaserBank(jsonObject.getString("purchaserBankAccountInfo") == null ? "" :
                jsonObject.getString("purchaserBankAccountInfo"));
        return fnainvoiceledger;
    }


    /**
     * 主表公共内容赋值
     *
     * @return 主表对象
     */
    public Fnainvoiceledger fnainvoiceledgerImportData(Integer typeInt, String id) {
        Fnainvoiceledger fnainvoiceledger = new Fnainvoiceledger();
        // OCR图片id
        // fnainvoiceledger.setImageDocId(IdUtils.simpleUUID());
        // id
        // fnainvoiceledger.setId(id);
        // todo 无 流程requestId
        // fnainvoiceledger.setRequestid(IdUtils.simpleUUID());
        // 发票类型
        fnainvoiceledger.setInvoicetype(typeInt);
        // 发票图片id
        fnainvoiceledger.setImageID("");
        // 扩展表字段 -------------------
        // 主键
        // fnainvoiceledger.setIdVo(id);
        return fnainvoiceledger;
    }


    /**
     * 台账明细表内容赋值
     *
     * @param obj 对象
     * @param id  主表ID
     * @return 明细表
     */
    public FnainvoiceledgerDetail fnainvoiceledgerDetailData(JSONObject obj, String id) {
        // 发票台账明细表
        // 遍历获取的结果集，将结果存入明细表中
        FnainvoiceledgerDetail fnainvoiceledgerDetail = new FnainvoiceledgerDetail();
        fnainvoiceledgerDetail.setId(IdUtils.simpleUUID());
        fnainvoiceledgerDetail.setMainid(id);
        // 货物或应税劳务、服务名称
        fnainvoiceledgerDetail.setInvoiceserviceyype(obj.getString("itemName") == null ? "" : obj.getString("itemName"
        ));
        // 金额
        try {

            fnainvoiceledgerDetail.setPricewithouttax(obj.getString("amount") == null ? BigDecimal.ZERO :
                    new BigDecimal(obj.getString("amount")));
            // 税率
            fnainvoiceledgerDetail.setTaxrate(obj.getString("taxRate") == null ? BigDecimal.ZERO :
                    Convert.toBigDecimal(obj.getString("taxRate").replace("%", ""), new BigDecimal("0")));
            // 税额
            fnainvoiceledgerDetail.setTax(obj.getString("tax") == null ? BigDecimal.ZERO :
                    Convert.toBigDecimal(obj.getString("tax"),BigDecimal.ZERO));
            // 单价
            fnainvoiceledgerDetail.setUnitprice(obj.getString("unitPrice") == null ? BigDecimal.ZERO :
                    Convert.toBigDecimal(obj.getString("unitPrice"),BigDecimal.ZERO));
            // 原始单价
            fnainvoiceledgerDetail.setOriginalUnitPrice(obj.getString("unitPrice") == null ? "" : obj.getString(
                    "unitPrice"));

        } catch (Exception e) {
            throw new ServiceException("执行失败,发票信息数据有误", 0);
        }
        // 数量
        fnainvoiceledgerDetail.setUnitnumber(obj.getString("quantity") == null ? "" : obj.getString("quantity"));
        fnainvoiceledgerDetail.setUnitnumber2(obj.getString("quantity") == null ? "" : obj.getString("quantity"));
        return fnainvoiceledgerDetail;
    }

    public Fnainvoiceledger commonInvoiceInsert(JSONObject dataInfo, Integer typeInt) {

        // 调整代码
        // 公共属性，每个方法首先进行公共属性的装载
        Fnainvoiceledger fnainvoiceledger = fnainvoiceledgerData(dataInfo, typeInt);
        // if(StringUtils.isNotBlank(dataInfo.getString("fare"))){
        //     fnainvoiceledger.setPricewithouttax(dataInfo.getString("fare"));
        // }

        // 火车票没有开票时间，采用开车时间作为开票时间
        // if (dataInfo.getString("departureTime") != null && !"".equals(dataInfo.getString("departureTime"))) {
        //     String dateStr = dataInfo.getString("departureTime");
        //     if (dateStr.contains("开")) {
        //         String fmtDate = DateUtils.formatStr(dataInfo.getString("departureTime") == null ? "" : dataInfo
        //         .getString("departureTime"));
        //         if (!fmtDate.isEmpty()) {
        //             fnainvoiceledger.setBillingdate(fmtDate);
        //         }
        //     } else {
        //         fnainvoiceledger.setBillingdate(dateStr);
        //     }
        // }

        // 获取主表ID 手动添加发票id=0不会检验图片资源
        if (dataInfo.containsKey("id") && dataInfo.getInteger("id") > 0) {
            // 更新数据但图片资源ImageDocId不进行更新
            fnainvoiceledger.setImageDocId(null);
            fnainvoiceledger.setId(dataInfo.getString("id"));
            fnainvoiceledger.setUpdateOperate(1);
            DataFormatUtil.invoiceFormat(typeInt, dataInfo, fnainvoiceledger);
            billDataUtil.fnaInvoiceLedgerMapper.updateFnainvoiceledger(fnainvoiceledger);
        } else {
            // 查询发票表是否存在相应发票号
            HashMap<String, Object> filterMap = new HashMap<>();
            filterMap.put("invoiceNumber", fnainvoiceledger.getInvoicenumber());
            Integer count = billDataUtil.fnaInvoiceLedgerMapper.getListRecordCount(filterMap);
            if (count > 0) {
                throw new ServiceException("执行失败,发票号已存在", 0);
            }
            try {
                fnainvoiceledger.setUpdateOperate(0);
                // 2024/6/27 根据不同类型的发票，将发票的时间设置到主表的billingDate字段
                DataFormatUtil.invoiceFormat(typeInt, dataInfo, fnainvoiceledger);
                Integer row = billDataUtil.fnaInvoiceLedgerMapper.addData(fnainvoiceledger);
            }catch (Exception e){
                throw new ServiceException("数据插入失败，请联系管理员", 0);
            }
        }
        String id = fnainvoiceledger.getId();
        fnainvoiceledger.setMainId(id);
        ArrayList<FnainvoiceledgerDetail> fnainvoiceledgerDetails = new ArrayList<>();
        // 台账明细表内容赋值
        if (dataInfo.containsKey("invoiceDetails") && StringUtils.isNotEmpty(dataInfo.getString("invoiceDetails"))) {

            JSONArray invoiceDetails = new JSONArray();
            try {
                invoiceDetails = JSON.parseArray(dataInfo.getString("invoiceDetails"));
            } catch (Exception e) {
                e.getMessage();
                System.out.println("发票详情解析失败");
            }
            if (null != invoiceDetails && invoiceDetails.size() > 0) {
                dataInfo.getJSONArray("invoiceDetails").forEach(e -> {
                    JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(e));

                    FnainvoiceledgerDetail fnainvoiceledgerDetail = fnainvoiceledgerDetailData(jsonObject, id);
                    fnainvoiceledgerDetails.add(fnainvoiceledgerDetail);
                });
                billDataUtil.fnaInvoiceLedgerMapper.addDataDetail(fnainvoiceledgerDetails);
            }

        }
        //发票费用项里面包含机票备注调为飞机票、包含住宿修改备注为住宿票
         if(null != fnainvoiceledgerDetails && fnainvoiceledgerDetails.size()>0){
             fnainvoiceledgerDetails.forEach(x->{
                 if(x.getInvoiceserviceyype().contains("机票")){
                     fnainvoiceledger.setRemark("飞机票");
                 }
                 if(x.getInvoiceserviceyype().contains("住宿")){
                     fnainvoiceledger.setRemark("住宿票");
                 }
                 //类型为增值税包含 "运输服务" 字样 备注调整旅客运输
                 if(fnainvoiceledger.getCategory().contains("增值税") && x.getInvoiceserviceyype().contains("运输服务")){
                     fnainvoiceledger.setRemark("旅客运输");
                 }
                 if(StringUtils.isBlank(fnainvoiceledger.getRemark())){
                     fnainvoiceledger.setRemark(fnainvoiceledgerDetails.get(0).getInvoiceserviceyype());
                 }
             });
         }
        billDataUtil.fnaInvoiceLedgerMapper.addDataVo(fnainvoiceledger);
        // 更新扩展表后id会调整成扩展表主键,需要重新赋值主表id
        fnainvoiceledger.setId(id);
        return fnainvoiceledger;
    }

}
